package win.zxshuo.www.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
import win.zxshuo.www.model.UserModel;
import win.zxshuo.www.repository.UserRepository;
import win.zxshuo.www.utils.StringUtils;

import java.util.Date;

/**
 * Author:rffanlab
 * Created:2018/4/8
 */
@Service
@Configurable
public class UserService {
    @Autowired
    UserRepository userRepository;

    /**
      * @Description: 添加新用户
      * @Author: RffanLAB.方露宇
      * @Params: username,password,mobile
      * @Returns: UserModel
      * @CreateDate: 2018/4/8
      */
    public UserModel addNewUser(String username,String password,String mobile) throws Exception {
        if (userRepository.findByMobile(mobile)!=null){
            throw new Exception("已经存在该手机号码了");
        }
        if (userRepository.findByUsername(username)!= null){
            throw new Exception("已经存在该用户名了");
        }
        UserModel userModel = new UserModel();
        userModel.setCreateDate(new Date());
        userModel.setMobile(mobile);
        userModel.setModifyDate(new Date());
        userModel.setPassword(StringUtils.encryptPwd(password));
        userModel.setToken(mkUniqueToken(4)); // 之所以只进行4次检查，是因为检查太多，浪费性能，而且存在4次32位随机字符串都有的概率实在太低了。如果有，果断报错好了
        userRepository.save(userModel);
        return userModel;
    }

    /**
      * @Description: 用户登录
      * @Author: RffanLAB.方露宇
      * @Params: username,password
      * @Returns: UserModel
      * @CreateDate: 2018/4/8
      */
    public UserModel checkUser(String username,String password) throws Exception {
        UserModel userModel = userRepository.findByUsername(username);
        if (userModel == null){
            throw new Exception("该用户不存在");
        }
        Boolean stat = StringUtils.comparePwd(password,userModel.getPassword());
        if (stat){
            // 如果正确就更新token 并返回token
            userModel.setToken(mkUniqueToken(4));
            userModel.setModifyDate(new Date());
            userRepository.save(userModel);
            return userModel;
        }else {
            return null;
        }
    }

    /**
     * 生成随机token作为用户登录的标识
     * @param checkTimes
     * @return
     */
    public String mkUniqueToken(Integer checkTimes){
        String token = StringUtils.randToken();
        UserModel userModel = userRepository.findByToken(token);
        if (userModel != null){
            if (checkTimes>0){
                return mkUniqueToken(checkTimes -1);
            }
        }
        return token;
    }


    /**
     * 通过token获取用户的实体类
     * @param token
     * @return
     */
    public UserModel getUserByToken(String token){
        return userRepository.findByToken(token);
    }



}
